package com.wetool.jpa;


import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.wetool.entity.Category;

/**
 * 商品分类仓库
 * @author lixin
 *
 */
@Repository
public interface CategoryRepo extends JpaRepository<Category, Long> {

	@Query("select t.id from Category t where merchantId = :merchantId and categoryLevel = :i")
	Long getByMerchantIdAndCategoryLevel(@Param("merchantId") Long merchantId,@Param("i") int i);

	@Query("select t from Category t where merchantId = :merchantId and t.categoryName like :name")
	Category getByMerchantIdAndlikeCategoryName(@Param("merchantId")Long merchantId,@Param("name") String name);

	List<Category> findByParentAndMerchantId(Category root, Long merchantId);

	@Query("select count(t.id) from Category t where (t.categoryName = replace(:name,' ','') or lower(t.categoryName) = lower(:name)) and t.merchantId = :merchantId  and t.parent.id = :parentId and t.isDeleted = false")
	Long countByName(@Param("name")String categoryName,@Param("merchantId")Long merchantId,@Param("parentId") Long parentId);

	@Query("select count(t.id) from Category t where t.parent.id = :parentId and t.isDeleted = :b")
	Long findByParentAndIsDeleted(@Param("parentId")Long categoryId,@Param("b") boolean b);

	@Query("select count(t.id) from Category t where (t.categoryName = replace(:name,' ','') or t.categoryName = :name) and t.merchantId = :merchantId and t.parent.id = :parentId and t.isDeleted = false and t.id <> :id")
	Long countByNameNot(@Param("name")String categoryName,@Param("merchantId")Long merchantId,@Param("parentId") Long parentId,@Param("id")Long id);

	@Query("select t.isLeaf from Category t where t.id = :id and t.isDeleted = false")
	Boolean getIsLeaf(@Param("id") Long categoryId);

	@Query("select c.id  from Category c where c.parent.id=:id and c.isDeleted = false")
	List<Long> getByPrentId(@Param("id") Long id);

}